package ru.sgu.codecenter.fidx.model;

import ru.sgu.codecenter.fidx.OperationFailedException;
import ru.sgu.codecenter.fidx.command.Command;

import java.io.File;
import java.util.concurrent.BlockingQueue;
import java.io.IOException;

public class IndexInterterThread extends Thread {
    private final BlockingQueue<File> queue;
    private final Engine engine;

    public IndexInterterThread(BlockingQueue<File> queue, Engine engine) {
        this.queue = queue;
        this.engine = engine;
        this.start();
    }

    @Override
    public void run() {
        try {
            while (true) {
                File file = queue.take();
                if (file.getName().equalsIgnoreCase(IndexInserter.FINALIZING_FILE_NAME)) {
                    queue.put(file);
                    break;
                }

                engine.insert(FileDocument.newFileDocument(file));
                Command.info("Update in the index \"" + file.getCanonicalPath() + "\".");
            }
        } catch (InterruptedException e) {
            throw new OperationFailedException("Unable to take file from a queue.", e);
        } catch (IOException e) {
            throw new OperationFailedException("Unable to open file for reading.", e);
        }
    }
}
